<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="title">文章管理系统</h2>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api'
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'))
      } else {
        callback()
      }
    }

    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [{ required: true, trigger: 'blur', message: '用户名必填' }],
        password: [
          { required: true, trigger: 'blur', message: '密码必填' },
          { validator: validatePass, trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 校验成功
          let { code, data } = await login(this.ruleForm)
          if (code === 20000) {
            // 提示用户登录成功
            this.$message({
              message: '登录成功',
              type: 'success',
            })
            // 将token存储到vuex
            this.$store.commit('setToken', data)
            // 跳转到后台首页
            let redirect = this.$route.query.redirect
            this.$router.push(redirect || '/')
          } else {
            this.$message({
              message: '用户名或密码错误',
              type: 'error',
            })
          }
        } else {
          // 校验失败
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
}
</script>

<style lang="scss" scoped>
.login-container {
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-image: linear-gradient(to bottom right, #4a9bdb, #5ea4da, #7987b3);

  .login-box {
    width: 500px;
    padding: 10px;
    background-color: rgba(0, 0, 0, 0.2);

    .el-input {
      width: 350px;
    }

    .title {
      font-size: 30px;
      margin: 10px 0;
      text-align: center;
    }

    .el-form {
      ::v-deep .el-form-item__label {
        color: #fff;
      }
    }
  }
}
</style>
